package com.apchernykh.rozhlasapp.ui.podcasts;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.apchernykh.ceskyrozhlas.basic.R;
import com.apchernykh.rozhlasapp.podcast.PodcastFeedHandler;
import com.apchernykh.rozhlasapp.ui.BaseDetailsFragment;
import com.apchernykh.rozhlasapp.ui.RozhlasAppBaseFragmentActivity;
import com.apchernykh.rozhlasapp.utils.ConditionalLog;
import com.apchernykh.types.PodcastFeedInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

//Could have beennamed podcastslist...
public class FeedDetailsFragment extends BaseDetailsFragment{
	/**
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 * 
	 * @param iStationInfo
	 * @param object
	 */

	public static BaseDetailsFragment newInstance(int iIndex) {
		BaseDetailsFragment aDetailsFragment = new FeedDetailsFragment();
		memorizeIndex(iIndex, aDetailsFragment);
		return aDetailsFragment;
	}



	@Override
	public View onCreateView(LayoutInflater iInflater, ViewGroup iContainer,
			Bundle iSavedInstanceState) {
		mDetailedView = null;
		PodcastFeedInfo aInfo = null;
		if (RozhlasAppBaseFragmentActivity.mApplicationModel.mFeeds.size() > getShownIndex())
		{
			mDetailedView = iInflater.inflate(R.layout.feed_details, iContainer, false);
			aInfo = RozhlasAppBaseFragmentActivity.mApplicationModel.mFeeds
					.get(getShownIndex());
		}
		if (iContainer != null && aInfo != null && mDetailedView != null) {
			resetFeedInfo(mDetailedView, aInfo);
			refreshFeedInfoAsync(mDetailedView, aInfo);
		}
		return mDetailedView;
	}

	private void refreshFeedInfoAsync(final View iView,
			final PodcastFeedInfo iInfo) {
		AsyncTask<Integer, Integer, Boolean> aTask = new AsyncTask<Integer, Integer, Boolean>() {

			@Override
			protected Boolean doInBackground(Integer... iParams) {
				populatePodcastFromURL(iInfo);
				return true;
			}

			@Override
			protected void onPostExecute(Boolean iUpdateSuccessful) {
				if (iUpdateSuccessful) {
					setFeedInfo(iView, iInfo);
				} else {
					ConditionalLog.d("onPostExecute", iInfo.getTitle()
							+ " scrolled out");
				}
			}
		};
		if(RozhlasAppBaseFragmentActivity.mApplicationModel.mInetInfo.isDownloadAllowed())
		{
			aTask.execute(0);
		}
	}

	protected void setFeedInfo(View iView, PodcastFeedInfo iInfo) {
			resetFeedInfo(iView, iInfo);
			iView.invalidate();
	}

	private void resetFeedInfo(View iView, PodcastFeedInfo iInfo) {

		TextView shortName = (TextView) iView.findViewById(R.id.podcast_name);
		TextView description = (TextView) iView
				.findViewById(R.id.podcast_description);

		populateList(iView, iInfo);

		shortName.setText(iInfo.getTitle());
		description.setText(iInfo.getDescription());

	}

	private void populateList(View iView, PodcastFeedInfo iFeed) {
		try {
			ListView view = (ListView) iView.findViewById(R.id.available_shows);
			if (!iFeed.getShows().isEmpty()) {
				mShowsListAdapter = new PodcastShowListAdapter(getActivity(),
						R.layout.podcast_item, iFeed.getShows());
					view.setAdapter(mShowsListAdapter);
			}
		} catch (Throwable e) {
			ConditionalLog.e("Exception in gui refresh", e);
		}
	}

	private PodcastShowListAdapter mShowsListAdapter;

	public void populatePodcastFromURL(PodcastFeedInfo iInitialInfo)
			throws RuntimeException {
		if (iInitialInfo == null) {
			return;
		}
		PodcastFeedHandler aRssHandler = new PodcastFeedHandler(iInitialInfo);
		SAXParserFactory aSaxParserFactory = SAXParserFactory.newInstance();
		aSaxParserFactory.setValidating(false);
		SAXParser aSaxParser;
		try {
			aSaxParser = aSaxParserFactory.newSAXParser();
		} catch (Exception e) {
			throw new RuntimeException("Could not create XML parser", e);
		}

		try {
			aSaxParser.parse(iInitialInfo.getUrl(), aRssHandler);
			iInitialInfo.setShows(aRssHandler.mLocalShowsList);
		} catch (Exception e) {
			ConditionalLog.e("Failed to parse feed", e);
		}
		ConditionalLog.d("Parsed RSS " + iInitialInfo.getUrl()
				+ " and retrieved " + iInitialInfo.getShows().size() + " feeds "
				+ aRssHandler.mUrlsCount + " urls total");
	}
}
